require('./filter')
var _ = require('lodash');
var Router = require('koa-router');
var service = require('./service');
var router = module.exports = new Router({
  prefix: '/store'
});

// 全部订单
router.get('/orders', loginRequired, function * (next) {
  var data = yield service.listOrder(this, {
    isVendor: 0,
    status: this.query.status || 0,
    projectIdList: this.session.projectIds
  });
  this.body = this.render('templates/orders.html', this.query, data);
});

router.get('/ajax/orders', loginRequired, function * (next) {

  // 店铺ID
  var data = yield service.listOrder(this, {
    isVendor: 0,
    status: this.query.status || 0,
    projectIdList: this.session.projectIds,
    pageSize: this.query.size,
    pageNo: this.query.page
  })
  this.body = this.render(200, this.query, data);
});

// 当日已处理订单
router.get('/todayorders', loginRequired, function * (next) {
  var data = yield service.getTodayOrder(this, {
    puserId: this.session.puser.partnerId
  });
  data.noNavbar = true
  this.body = this.render('templates/orders.html', this.query, data);
});

router.get('/ajax/todayorders', loginRequired, function * (next) {
  var data = yield service.getTodayOrder(this, {
    puserId: this.session.puser.partnerId,
    pageSize: this.query.size,
    pageNo: this.query.page
  })
  this.body = this.render(200, this.query, data);
});

// 当日已处理店铺订单
router.get('/todayVendorOrders', loginRequired, function * (next) {
  var data = yield service.getTodayProviderOrder(this, {
    vendorId: this.session.vendorId
  });
  data.noNavbar = true
  this.body = this.render('templates/orders.html', this.query, data);
});

router.get('/ajax/todayVendorOrders', loginRequired, function * (next) {
  var data = yield service.getTodayProviderOrder(this, {
    vendorId: this.session.vendorId,
    pageSize: this.query.size,
    pageNo: this.query.page
  })
  this.body = this.render(200, this.query, data);
});

// 店铺订单
router.get('/storeorders', loginRequired, function * (next) {
  var projectIds = this.query.projectId
  var projects = projectIds ? {
    projectIdList: projectIds.split(',')
  } : [];
  // 店铺ID
  var data = yield service.listOrder(this, {
    isVendor: 1,
    vendorId: this.session.vendorId,
    status: this.query.status || 0,
    projectIdList: projects.projectIdList
  })
  data.isVendor = true
  this.body = this.render('templates/orders.html', this.query, data);
});

router.get('/ajax/storeorders', loginRequired, function * (next) {
  // 店铺ID
  var data = yield service.listOrder(this, {
    isVendor: 1,
    status: this.query.status || 0,
    vendorId: this.session.vendorId,
    pageSize: this.query.size,
    pageNo: this.query.page
  })
  this.body = this.render(200, this.query, data);
});

// 社区列表 TODO  下一版
/*
router.get('/projects', function * (next) {
  var data = yield service.getProjects(this, {
    'puserId': 'ff808181535604860153560486e30000'
  })
  this.body = this.render('templates/projects.html', data)
})
*/

// 订单搜索
router.get('/ordersearch', loginRequired, function * (next) {
  var keyWords = this.session['orderSearch:KeyWords'] || ''
  keyWords = keyWords && keyWords.split(',')
  this.body = this.render('templates/ordersearch.html', {
    keyWords: keyWords
  })
});

router.get('/ordersearch/result', loginRequired, function * (next) {
  var data = yield service.searchOrder(this, this.query)
    // 历史搜索
  var keyWords = this.session['orderSearch:KeyWords'] || ''
  keyWords = keyWords ? keyWords.split(',') : []
  if (this.query.keyWord) {
    var atIndex = keyWords.indexOf(this.query.keyWord)
    atIndex == -1 ?
      keyWords.unshift(this.query.keyWord) :
      (function () {
      keyWords.unshift(keyWords.splice(atIndex, 1)[0])
    })()
  }
  var readyKeyWords = keyWords.splice(0, 10)
  this.session['orderSearch:KeyWords'] = readyKeyWords.join(',');

  data.noNavbar = true
  this.body = this.render('templates/orders.html', this.query, data)
});

router.get('/ajax/keywords/clear', loginRequired, function * (next) {
  this.session['orderSearch:KeyWords'] = null
  this.body = this.render(200, {
    message: '已清空'
  })
});

router.get('/ajax/ordersearch', loginRequired, function * (next) {
  var data = yield service.searchOrder(this, this.query)
  this.body = this.render(200, this.query, data);
});

// 订单详情
router.get('/order/:id', loginRequired, function * (next) {
  var vendorInfo = this.session.partners.filter(function (p) {
      return p.partnerType == 'sh'
    })[0]
    // 订单ID
  var data = yield service.detailOrder(this, {
    orderCode: this.params.id
  })
  this.body = this.render('templates/order.html', {
    vendorId: vendorInfo && vendorInfo.partnerId
  }, data.entity);
});

// 订单支付
router.get('/cashier/paytype/:orderCode', loginRequired, function * (next) {
  var data = yield service.detailOrder(this, {
    orderCode: this.params.orderCode
  })

  this.body = this.render('templates/cashier.html', data.entity)
});

// 订单支付二维码
router.get('/cashier/paycode/:orderCode', loginRequired, function * (next) {
  var data = yield service.orderPayQrCode(this, {
    orderCode: this.params.orderCode,
    payPath: 'cashier/gotopay'
  })

  this.body = this.render('templates/orderpaycode.html', this.params, data);
});

// 是否扫码支付成功
router.get('/ajax/bepaid/:orderCode', loginRequired, function * (next) {
  var data = yield service.judeOrderIsPay(this, {
    orderCode: this.params.orderCode
  })

  this.body = this.render(200, data)
});

// 订单收款成功
router.get('/payordersuccess', loginRequired, function * (next) {
  this.body = this.render('templates/payordersuccess.html', this.query)
});

// 准备发货
router.get('/delivery/:orderCode', loginRequired, function * (next) {
  this.body = this.render('templates/delivery.html', this.params, this.query)
});

// 确认发货
router.post('/delivery', loginRequired, function * (next) {
  var params = this.request.body
    // 0 快递 1 自行配送
  switch (params.deliverType) {
  case 'delivery':
    params.deliverType = 1
    delete params['logisticsName']
    delete params['logisticsCode']
    break;
  case 'sendout':
    params.deliverType = 0;
    delete params['deliverMobile']
    delete params['deliverName']
    break;
  default:
    break;
  }

  params.puserId = this.session.puser['partnerId']

  var result = yield service.setLogistics(this, params)
  this.redirect('/store/storeorders')
});

// 收款
router.get('/checkout', loginRequired, function * (next) {
  var providerId = this.session.vendorId || 0
  var shopId = this.query.shopId
  var entity = null

  var lastShopEntity = yield service.lastStore(this, {
    'providerId': providerId
  })
  var lastShopId = lastShopEntity.shopBean.id

  shopId = shopId || lastShopId

  var sData = yield service.listStore(this, {
    'providerId': providerId
  })

  sData.list.forEach(function (s) {
    if (sData.list.length == 1 || s.id == shopId) {
      return entity = s
    }
  })

  var renderData = {
    providerId: providerId,
    count: sData.list ? sData.list.length : 0,
    entity: entity
  }

  this.body = this.render('templates/checkout.html', renderData)
});

// 现金收款
router.get('/cashCollectFees', loginRequired, function * (next) {

  var puserId = '';
  this.session.partners.forEach(function (user) {
    if (user.partnerType == 'bs') {
      return puserId = user.partnerId
    }
  });
  var data = yield service.cashCollectFees(this, {
    orderCode: this.query.orderCode,
    puserId: puserId
  });

  if (data.fail) {
    this.body = this.render(500, data)
  }
  else {
    this.body = this.render(200, data)
  }
});

// 店铺列表
router.get('/stores/:id', loginRequired, function * (next) {
  var sData = yield service.lastStore(this, {
    'providerId': this.params.id
  });

  var data = {
    'prevId': sData.shopBean.id,
    'stores': yield service.listStore(this, {
      'providerId': this.params.id
    }),
    'providerId': this.params.id
  };
  this.body = this.render('templates/stores.html', this.query, data)
});

// 付款码
router.post('/paycode', loginRequired, function * (next) {

  var data = yield service.createQrcode(this, _.extend(this.request.body, {
    url: '/cashier/payordercreate'
  }));
  if (data.qrCodeId) {
    data.price = this.request.body.price
    this.body = this.render('templates/paycode.html', data)
  };
});

// 店铺收款二维码支付状态
router.get('/ajax/paystatus/:qrCodeId', loginRequired, function * (next) {
  var data = yield service.monitorQrCode(this, {
    'qrCodeId': this.params.qrCodeId
  });
  this.body = this.render(200, data);
});

// 店铺收款成功
router.get('/paysuccess/:qrCodeId', loginRequired, function * (next) {
  var data = yield service.monitorQrCode(this, {
    'qrCodeId': this.params.qrCodeId
  });
  this.body = this.render('templates/paysuccess.html', data.entity)
});

// 历史付款
router.get('/payhistory', loginRequired, function * (next) {
  var data = yield service.listPayOrder(this, {
    providerId: this.session.vendorId,
    memberId: this.session.member.memberId,
    pageSize: 20,
    pageNo: 1
  });
  this.body = this.render('templates/payhistory.html', this.params, data)
});

router.get('/ajax/payhistory', loginRequired, function * (next) {
  var data = yield service.listPayOrder(this, {
    providerId: this.session.vendorId,
    memberId: this.session.member.memberId,
    pageSize: this.query.size,
    pageNo: this.query.page
  })
  this.body = this.render(200, data)
});